package swimv2gm.client.abilities;

import java.io.IOException;
import java.util.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.domain.Ability;
import swimv2gm.bl.util.UserData;
import swimv2gm.bl.session.AbilityManager;
import swimv2gm.bl.session.FriendshipManager;

/**
 * Servlet incaricata di ottenere l'elenco di utenti che hanno dichiarato una
 * determinata competenza, eventualmente restringendo la selezioni agli amici
 * dell'utente connesso.
 * 
 * @author Gallesio Matteo
 */
public class UsersWithAbility extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		AbilityManager man;
		try {
			man = (AbilityManager)InitialContext.doLookup("AbilityManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}
		long cid = -1;

		Ability a;
		try {
			cid = Long.parseLong(request.getParameter("cid"));
			a = man.getAbility(cid);
		} catch (IllegalArgumentException e) {
			a = null;
		}

		List<UserData> users = null;

		// the ability exists
		if (a != null) {
			if (request.getParameter("friends") != null && Boolean.parseBoolean(request.getParameter("friends"))
					&& request.getSession().getAttribute("user") != null) {
				FriendshipManager fman;
				try {
					fman = (FriendshipManager)InitialContext.doLookup("FriendshipManager");
				} catch (NamingException e) {
					response.sendError(500);
					return;
				}
				long uid = (Long)request.getSession().getAttribute("user");
				users = fman.friendsWithAbility(uid,cid);
				request.setAttribute("friends",true);
			}
			else {
				users = man.getUserData(cid);
			}

			request.setAttribute("aname",a.getNome());
		}

		// remains null if the ability was not found
		request.setAttribute("users",users);

		request.getRequestDispatcher("/search/usersWithAbility.jsp").forward(request,response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doGet(request,response);
	}

}
